package com.cms.controller.front;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.BooleanUtils;

import com.cms.Feedback;
import com.cms.entity.Receiver;
import com.cms.routes.RouteMapping;


/**
 * Controller - 收货地址
 * 
 * 
 * 
 */
@RouteMapping(url = "/receiver")

public class ReceiverController extends BaseController{

	/**
	 * 添加
	 */
	public void add(){
		render("/templates/"+getTheme()+"/"+getDevice()+"/receiver_add.html");
	}
	
	/**
	 * 保存
	 */
	public void save(){
		Receiver receiver = getModel(Receiver.class,"",true);
		receiver.setCreateDate(new Date());
		receiver.setModifyDate(new Date());
		receiver.setMemberId(getCurrentMember().getId());
		receiver.setIsDefault(BooleanUtils.toBoolean(receiver.getIsDefault()));
		if(receiver.getIsDefault()){
			Receiver defaultReceiver=new Receiver().dao().findDefault(getCurrentMember().getId());
			if(defaultReceiver!=null && defaultReceiver.getIsDefault()){
				defaultReceiver.setIsDefault(false);
				defaultReceiver.update();
			}
		}
		receiver.save();
		Map<String,Object> result = new HashMap<>();
		result.put("receiverId",receiver.getId());
		renderJson(Feedback.success(result));
	}
	
	/**
     * 编辑
     */
    public void edit() {
        Long id = getParaToLong("id");
        setAttr("receiver", new Receiver().dao().findById(id));
        render("/templates/"+getTheme()+"/"+getDevice()+"/receiver_add.html");
    }
	
	/**
	 * 更新
	 */
	public void update(){
        Receiver receiver = getModel(Receiver.class,"",true);
        receiver.setModifyDate(new Date());
        receiver.setIsDefault(BooleanUtils.toBoolean(receiver.getIsDefault()));
        if(receiver.getIsDefault()){
            Receiver defaultReceiver=new Receiver().dao().findDefault(getCurrentMember().getId());
            if(defaultReceiver!=null && defaultReceiver.getIsDefault()){
                defaultReceiver.setIsDefault(false);
                defaultReceiver.update();
            }
        }
        receiver.update();
        renderJson(Feedback.success(new HashMap<>()));
	}
	
	/**
     * 列表
     */
    public void list(){
        setAttr("receivers",new Receiver().dao().findList(getCurrentMember().getId()));
        render("/templates/"+getTheme()+"/"+getDevice()+"/receiver_list.html");
    }
    
	/**
     * 删除
     */
    public void delete() {
        Long id = getParaToLong("id");
        new Receiver().dao().deleteById(id);
        renderJson(Feedback.success(new HashMap<>()));
    }
	
}
